package com.moon.springcloud_zuul.limit;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

@Component
public class RateLimitZuulFilter extends ZuulFilter {
    //同一時刻允許請求的個數 3個
    private RateLimiter rateLimiter = RateLimiter.create(2);
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
     //   return 3;
    }

    @Override
    public boolean shouldFilter() {
        //可以考慮弄個開關
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        if(!rateLimiter.tryAcquire()){
            HttpStatus tooManyRequests = HttpStatus.TOO_MANY_REQUESTS;
            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setStatus(tooManyRequests.value());
            requestContext.setSendZuulResponse(false);
            throw new ZuulException(tooManyRequests.getReasonPhrase(),tooManyRequests.value(),tooManyRequests.getReasonPhrase());
        }
        System.out.println("ik");
        return null;
    }
}
